"use client"

import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import {
  ArrowLeft,
  Calendar,
  User,
  Clock,
  CheckCircle,
  AlertTriangle,
  Printer,
  Copy,
} from "lucide-react"
import type { Ticket } from "@/types/tickets"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

const formatDate = (dateString: string | null) => {
  if (!dateString) return "N/A"
  const date = new Date(dateString)
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  })
}

const StatusBadge = ({ status }: { status: Ticket["status"] }) => {
  const statusMap = {
    已完成: "bg-green-100 text-green-800",
    进行中: "bg-blue-100 text-blue-800",
    待执行: "bg-yellow-100 text-yellow-800",
    已作废: "bg-red-100 text-red-800",
  }
  return (
    <Badge
      variant="outline"
      className={`border-none text-sm px-3 py-1 ${
        statusMap[status as keyof typeof statusMap]
      }`}
    >
      {status}
    </Badge>
  )
}

export default function TicketDetail({ ticket }: { ticket: Ticket | undefined }) {
  if (!ticket) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-50">
        <Card className="w-full max-w-md p-8 text-center">
          <AlertTriangle className="h-12 w-12 text-red-500 mx-auto" />
          <h2 className="mt-4 text-xl font-semibold">未找到操作票</h2>
          <p className="mt-2 text-gray-600">无法加载该操作票的详情。</p>
          <Link href="/tickets">
            <Button className="mt-4">返回列表</Button>
          </Link>
        </Card>
      </div>
    )
  }

  const handlePrint = (printType: "before" | "after") => {
    window.open(`/tickets/${ticket.id}/print/${printType}`, "_blank")
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4 sm:p-6 lg:p-8">
      <div className="max-w-4xl mx-auto">
        <header className="flex items-center justify-between mb-6">
          <Link
            href="/tickets"
            className="flex items-center text-sm font-medium text-gray-600 hover:text-gray-900"
          >
            <Button variant="ghost" className="p-0 h-auto">
              <ArrowLeft className="w-5 h-5 mr-2" />
              返回
            </Button>
          </Link>
          <div className="flex items-center gap-2">
            <h1 className="text-xl font-bold text-gray-800">操作票详情</h1>
            <StatusBadge status={ticket.status} />
          </div>
          <div className="flex items-center space-x-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline">
                  <Printer className="w-4 h-4 mr-2" />
                  打印
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => handlePrint("before")}>
                  打印作业前票据
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handlePrint("after")}>
                  打印作业后票据
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            <Button>
              <Copy className="w-4 h-4 mr-2" />
              复制为新票
            </Button>
          </div>
        </header>

        <div className="space-y-6">
          {/* 基本信息 */}
          <Card>
            <CardHeader>
              <CardTitle>基本信息</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-x-4 gap-y-6 text-sm">
                <div>
                  <p className="text-gray-500 mb-1">操作票编号</p>
                  <p className="font-semibold text-gray-800">{ticket.id}</p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">操作票类型</p>
                  <p className="font-semibold text-gray-800">{ticket.type}</p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">作业地点</p>
                  <p className="font-semibold text-gray-800">
                    {ticket.location}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">作业部门</p>
                  <p className="font-semibold text-gray-800">贴主控</p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">申请人</p>
                  <p className="font-semibold text-gray-800 flex items-center">
                    <User className="w-3 h-3 mr-1.5" />
                    {ticket.applicant}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">申请时间</p>
                  <p className="font-semibold text-gray-800 flex items-center">
                    <Calendar className="w-3 h-3 mr-1.5" />
                    {formatDate(ticket.applicationTime)}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">操作人</p>
                  <p className="font-semibold text-gray-800 flex items-center">
                    <User className="w-3 h-3 mr-1.5" />
                    {ticket.operator}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">监护人</p>
                  <p className="font-semibold text-gray-800 flex items-center">
                    <User className="w-3 h-3 mr-1.5" />
                    {ticket.supervisor}
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 任务信息 */}
          <Card>
            <CardHeader>
              <CardTitle>任务信息</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-sm">
                <div>
                  <p className="text-gray-500 mb-1">任务名称</p>
                  <p className="font-semibold text-gray-800">
                    {ticket.operationType}
                  </p>
                </div>
                <div>
                  <p className="text-gray-500 mb-1">作业目标</p>
                  <p className="font-semibold text-gray-800">{ticket.target}</p>
                </div>
                <div className="col-span-2">
                  <p className="text-gray-500 mb-1">作业条件</p>
                  <p className="font-semibold text-gray-800">
                    确认相关作业已结束，受电弓降下，无雷雨天气。（送电作业前确认平台人员及设备清出）
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 执行详情 */}
          <Card>
            <CardHeader>
              <CardTitle>执行详情</CardTitle>
            </CardHeader>
            <CardContent>
              {ticket.status === "待执行" ? (
                <div className="text-center py-8 text-gray-500">
                  <Clock className="w-8 h-8 mx-auto mb-2" />
                  <p>该操作票正在等待执行，暂无执行信息。</p>
                </div>
              ) : (
                <div className="space-y-4">
                  <div>
                    <h4 className="font-semibold text-gray-700 mb-2">
                      安全措施及注意事项
                    </h4>
                    <ul className="space-y-2 list-decimal list-inside pl-2 text-sm">
                      {ticket.safetyMeasures.map(
                        (measure: { item: string }, index: number) => (
                          <li key={index} className="flex items-start">
                            <CheckCircle className="w-4 h-4 mr-2 mt-0.5 text-green-500 flex-shrink-0" />
                            <span>{measure.item}</span>
                          </li>
                        )
                      )}
                    </ul>
                  </div>
                  <div className="border-t border-gray-200 pt-4">
                    <h4 className="font-semibold text-gray-700 mb-2">
                      操作步骤
                    </h4>
                    <ol className="space-y-2 text-sm">
                      {ticket.operations.map(
                        (op: {
                          step: number
                          action: string
                          status: string
                        }) => (
                          <li
                            key={op.step}
                            className="flex items-start p-2 rounded-md transition-colors hover:bg-gray-100"
                          >
                            <div className="flex-shrink-0 w-5 h-5 bg-blue-500 text-white text-xs font-bold rounded-full flex items-center justify-center mr-3 mt-0.5">
                              {op.step}
                            </div>
                            <div className="flex-grow">
                              <p className="text-gray-800">{op.action}</p>
                              <div className="flex items-center text-xs text-gray-500 mt-1">
                                <Clock className="w-3 h-3 mr-1" />
                                <span>{formatDate(ticket.executionTime)}</span>
                                <span className="mx-2">|</span>
                                <User className="w-3 h-3 mr-1" />
                                <span>{ticket.operator}</span>
                              </div>
                            </div>
                            <CheckCircle
                              className={`w-5 h-5 ml-4 flex-shrink-0 ${
                                op.status === "completed"
                                  ? "text-green-500"
                                  : "text-gray-300"
                              }`}
                            />
                          </li>
                        )
                      )}
                    </ol>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
} 